package com.efounder.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.model.Constant;
import com.efounder.chat.model.NoticeCountEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.model.UpdateResEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.OSPService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.service.WatchService;
import com.efounder.chat.utils.SPUtils;
import com.efounder.chat.utils.ServiceUtils;
import com.efounder.chat.widget.BadgeView;
import com.efounder.common.floatwindow.FloatWindowService;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JResponseObject;
import com.efounder.forwechat.BaseApp;
import com.efounder.fragment.LeftDrawerFragment;
import com.efounder.fragment.MainFragment;
import com.efounder.fragment.MenuFragment.RefreshforDefineMenu;
import com.efounder.fragment.PagerSlidingTab2Fragment;
import com.efounder.fragment.PagerSlidingTabFragment;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.model.APKUpdateManager;
import com.efounder.model.ClearBadgeEvent;
import com.efounder.model.LoginUtil;
import com.efounder.model.LoginUtilInterface;
import com.efounder.model.RESUpdateManager;
import com.efounder.model.RefreshViewEvent;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;
import com.efounder.skin.CustomSDCardLoader;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.AppContext;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.LogOutUtil;
import com.efounder.util.LoginManager;
import com.efounder.util.MenuGnqxUtil;
import com.efounder.util.MyStaticWebView;
import com.efounder.util.PackgeFileCheckUtil;
import com.efounder.util.TangZuUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.dialog.DisclaimerDialog;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.widget.EFImage;
import com.efounder.widget.ESPWebView;
import com.efounder.widget.TabBarNew;
import com.efounder.widget.TabBarNew.OnCurrentTabChangedListener;
import com.pansoft.resmanager.ResFileManager;
import com.pansoft.resmanager.ResLoadManager;
import com.pansoft.start.LoginCheckManager;
import com.pansoft.xmlparse.OptionParser;
import com.tencent.bugly.crashreport.CrashReport;
import com.utilcode.util.AppUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.ToastUtils;
import com.zhuiji7.filedownloader.download.DownLoadService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import q.rorbin.badgeview.QBadgeView;
import skin.support.SkinCompatManager;

import static com.efounder.chat.model.Constant.SKIN_DIR;
import static com.efounder.forwechat.BaseApp.context;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;


/**
 * 底部 activity
 */
@SuppressWarnings("unused")
public class TabBottomActivity extends AbActivity implements OnCurrentTabChangedListener, RefreshforDefineMenu {

    private static final String TAG = "TabBottomActivity";
    //读取主菜单配置的标签
    public static final String KEY_MENU_ROOT = "menuRoot";
    //默认展示页(打开应用默认展示第一个fragment)
    private final static int DEFAULT_ININT_TAB_INDEX = 0;

    //主菜单
    private List<StubObject> mainMenuList;
    //默认的主菜单，现在没有使用到
    private List<StubObject> defaultMenuList;
    //底部菜单导航栏
    private AbBottomBar mBottomBar = null;
    //当前Tab页面索引
    public int currentTabIndex;
    private FragmentManager fragmentManager;
    static TabBottomActivity mySelf;
    //放置底部菜单的view
    private TabBarNew tabBarView;
    //将要显示的fragment
    private BaseFragment willShowFragment;
    //将要隐藏的fragment
    private BaseFragment willHideFragment;
    //当前显示的菜单index
    private int currentIndex = DEFAULT_ININT_TAB_INDEX;

    private TabBottomActivityResultListener onTabBottomActivityResultListener;
    //以前给糖足项目使用的，现在用不到
    private DisclaimerDialog disclaimerDialog;
    //上一次点击返回按钮的时间
    private long lastClickBackTime;
    // 缓存主菜单对应的Fragments
    public BaseFragment[] cachedFragments;
    //微信聊天id 和password
    private String chatUserID;
    private String chatPassword;

    //记录点击菜单的次数
    private int recordClickMenuNum;
    //app升级管理
    private APKUpdateManager apkUpdateManager = new APKUpdateManager();
    //线程锁
    final Object synObj = new Object();
    //反射的push推送相关
    private ReflectUtils reflectPushManager;


    public static void start(Context context) {
        Intent starter = new Intent(context, TabBottomActivity.class);
        starter.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(starter);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //bugly设置登录用户id,这样我们可以知道哪个用户闪退
        CrashReport.setUserId(EnvironmentVariable.getUserName());
        //FIXME 加载配置文件文件
        Registry.init(ResFileManager.PACKAGE_DIR);
        initReactNativeAndStatusMode();
        //设置不可滑动返回
        getSwipeBackLayout().setEnableGesture(false);
        //2.XXX-为activity注册的默认 音频通道 。
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setAbContentView(R.layout.tab_bottom_n);
        chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID, "");
        chatPassword = EnvironmentVariable.getProperty(CHAT_PASSWORD, "");

        //检查配置文件是否完整
        boolean profileIsFull = PackgeFileCheckUtil.checkFileIsFull(AppContext.getInstance());
        if (TextUtils.isEmpty(chatUserID) || !profileIsFull || TextUtils.isEmpty(chatPassword)) {
            try {
                LogUtils.e("默认资源文件不完整，或者用户信息不存在，请检查资源文件");
                //重启应用，这样我们会重新进入登陆界面
                EnvironmentVariable.setPassword("");
                AppUtils.relaunchApp(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        BadgeUtil.initBadge();

        // 设置默认显示的标签页
        fragmentManager = getSupportFragmentManager();
        initView();
        String isLoadStaticWebView = EnvironmentVariable.getProperty("isLoadStaticWebView");
        if ((null != isLoadStaticWebView && !isLoadStaticWebView.equals("1"))) {
            initWebview();
        }

        getTitleBar().setVisibility(View.GONE);
        initData();
        initBadge();
        //注册监听
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //TODO
        // 从服务器请求联系人和群组数据

        try {

            int newFriendCount = WeChatDBManager.getInstance().getNewFriendUnread();
            int groupNoticeCount = WeChatDBManager.getInstance().getGroupNoticveUnreadCount();
            EventBus.getDefault().post(new NoticeCountEvent(newFriendCount, groupNoticeCount));

            //从服务器请求联系人和群组数据,以及自己的个人信息
            GetHttpUtil.getUserInfo(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)),
                    TabBottomActivity.this, new GetHttpUtil.GetUserListener() {
                        @Override
                        public void onGetUserSuccess(User user) {
                            EnvironmentVariable.setProperty(Constants.KEY_NICK_NAME, user.getNickName());
                        }

                        @Override
                        public void onGetUserFail() {

                        }
                    });
            GetHttpUtil.getUserData(this);
            GetHttpUtil.getGroupListByLoginId(this, null);
            GetHttpUtil.getAllOfficialNumber(this);
        } catch (Exception e) {
            e.printStackTrace();
        }


        String username = EnvironmentVariable.getUserName();
        String password = EnvironmentVariable.getPassword();
        if (username == null) {
            try {
                Toast.makeText(AppContext.getInstance(), "用户名失效，请重新登录", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setClass(this, Class.forName("com.efounder.activity.Login_withTitle"));
                stopAllService();
                startActivity(intent);
                this.finish();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return;
        }

//        if(!((BaseApp)getApplicationContext()).isSystemInited()){
//
//            initBadge();
//        }


        //开启线程加载是否升级，检查权限的功能

        String loginType = EnvironmentVariable.getProperty("LoginType");
        if (null != loginType && loginType.equals("0")) {
            //开始检查是否更新版本
            if (!getIntent().hasExtra("unDoCheck")) {
//                LoginByRestFulManager loginByRestFulManager = new LoginByRestFulManager(1);
//                loginByRestFulManager.loginBegin(TabBottomActivity.this, username, password);

                LoginCheckManager loginCheckManager = new LoginCheckManager(this);
                loginCheckManager.checkVersionAfterLogin(LoginCheckManager.TYPE_NOT_LOGIN);
            }

        } else {
            //TODO 此处初始化EAI，具体位置，以后再考虑下。

            EAI.Protocol = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE);
            EAI.Server = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS);
            EAI.Port = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT);
            EAI.Path = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH);
            EAI.Service = Constant.EAI_SERVICE;


            LoginUtil loginUtil = new LoginUtil();

            loginUtil.start(username, password,
                    new LoginUtilInterface() {
                        @Override
                        public void startProgress() {
                        }

                        @Override
                        public void loginSuccess(JResponseObject result) {
                            Map<?, ?> responseMap = result.getResponseMap();
                            JResponseObject pingtaiRO = (JResponseObject) responseMap.get("pingtai");
                            EFDataSet weChatDataSet = (EFDataSet) responseMap.get("extrawx");//获取返回的聊天id密码
                            Map<?, ?> pingtaiResponseMap = pingtaiRO.getResponseMap();

                            if (responseMap == null) {
                                ToastUtil.showToast(AppContext.getInstance(), "登录失败，请联系管理员。");
                                return;
                            } else {
                                pingtaiRO = (JResponseObject) responseMap.get("pingtai");
                            }
                            if (pingtaiRO != null) {
                                pingtaiResponseMap = pingtaiRO.getResponseMap();
                                ///LoginManager.checkGNQXBYOSP(pingtaiResponseMap);//保存服务器返回的功能权限
                                String gnqxSetttingModel = EnvironmentVariable.getProperty("GNQXSET");
                                if (null != gnqxSetttingModel && gnqxSetttingModel.equals("0")) {
                                    //checkGNQXBYOSP(result);
                                    LoginManager.checkGNQXBYOSP(pingtaiResponseMap);
                                } else if (null != gnqxSetttingModel && gnqxSetttingModel.equals("2")) {
                                    LoginManager.checkGNQX(result);
                                }
                            } else {
                                ToastUtil.showToast(AppContext.getInstance(), "登录失败，请联系管理员。");
                                return;
                            }
                            if (weChatDataSet != null) {
                                //存储微信聊天密码
                                List<EFRowSet> weChatEfRowSets = weChatDataSet.getRowSetArray();
                                EFRowSet weChatRowSet = weChatEfRowSets.get(0);
                                //// TODO: 2017/12/20 保存糖足应用的一些信息
                                TangZuUtil.saveTangZuInfo(weChatRowSet);
                                chatPassword = weChatRowSet.getString("F_IM_PASSWORD", "");
                                if (!("").equals(chatUserID) && !("").equals(chatPassword)) {
                                    String chatUserIDLocal = EnvironmentVariable.getProperty(CHAT_USER_ID);

                                    //处理后台更新他的消息ID的特殊情况
                                    if (chatUserID != chatUserIDLocal) {
                                        try {
                                            Toast.makeText(AppContext.getInstance(), "用户名失效，请重新登录", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent();
                                            intent.setClass(TabBottomActivity.this, Class.forName("com.efounder.activity.Login_withTitle"));
                                            // stopAllService();
                                            LogOutUtil.stopLocalIMService(TabBottomActivity.this);
                                            startActivity(intent);
                                            TabBottomActivity.this.finish();
                                        } catch (ClassNotFoundException e) {
                                            e.printStackTrace();
                                        }
                                        return;
                                    }
                                    EnvironmentVariable.setProperty(CHAT_USER_ID, chatUserID);
                                    EnvironmentVariable.setProperty(CHAT_PASSWORD, chatPassword);
                                }

                                String group_id = weChatRowSet.getString("group_id", "");
                                EnvironmentVariable.setProperty(chatUserID + "workgroup", group_id);

                                //处理聊天的权限
                                LoginManager.checkChatPermission(result);

                            }
                            //开始检查是否更新版本
                            if (!getIntent().hasExtra("unDoCheck")) {
//                            loginResultRO = result;
//                            boolean isNeedUpdateAPP = CheckAPKVerion(result);
                                apkUpdateManager.CheckAPKVerion(TabBottomActivity.this, result, CheckUpdateHandler);
                            }
                        }

                        @Override
                        public void loginFailed(String errorString) {
                            //密码错误   --- 密码失效
                            try {
                                Toast.makeText(AppContext.getInstance(), errorString, Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent();
                                stopAllService();
                                intent.setClass(TabBottomActivity.this, Class.forName("com.efounder.activity.Login_withTitle"));
                                startActivity(intent);
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void exception(String exceptionString) {
                            ToastUtil.showToast(AppContext.getInstance(), exceptionString + "，请稍后重试。");
                            LoadingDataUtilBlack.dismiss();
                        }
                    }
            );
        }

        //初始化华为推送，必须放到oncreate里面
        initHuaweiPush();
    }

    private void initHuaweiPush() {
        try {
            if (reflectPushManager == null) {
                reflectPushManager = ReflectUtils.reflect("com.efounder.push.PushManager").newInstance(this);
            }
            reflectPushManager.method("initPushTokenAndConnect");
        } catch (Exception e) {
        }
    }


    /**
     * 初始化rn和状态栏字体颜色
     * 这个代码项目中其实已经用不到了，老项目使用的，所以暂时保留
     */
    @Deprecated
    private void initReactNativeAndStatusMode() {
        //*************************初始化RN颜色**********start***************
        Map<String, String> interest = OptionParser.getInstance()
                .getElementById("RNTitleBackGround");
        if (null != interest) {
            String RNTitleBackGround = interest.get("value");
            if (RNTitleBackGround != null) {
                EnvironmentVariable.setProperty("navcolor", RNTitleBackGround);
            }
        }

        //判断状态栏字体是否需要设置成dark
        Map<String, String> statusDark = OptionParser.getInstance()
                .getElementById("statusDark");
        if (null != statusDark) {
            String statusDarkValue = statusDark.get("value");
            SharedPreferences mSharedPreferences = getSharedPreferences("mSharedPreferences", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = mSharedPreferences.edit();
            if (statusDarkValue != null) {
                edit.putString("statusDarkValue", statusDarkValue);
                edit.commit();
            }
        }
    }

    private void initBadge() {
        if (null == mainMenuList) {
            return;
        }
        //不在列表里显示角标
        String chatIdNotReachedByChatListItem = "";
        for (int i = 0; i < mainMenuList.size(); i++) {
            if (i >= 5) {
                //最多只有五个菜单
                return;
            }
            StubObject stubObject = mainMenuList.get(i);
            String id = (String) stubObject.getID();
            //配置文件是否该tab的角标可拖动
            boolean draggable = stubObject.getString("badgeDraggable", "false").equals("true");
            List chatIDs = BadgeUtil.badgeMap.get(id);

            int unReadCount = BadgeUtil.getCount(id);

            EFImage efImage = tabBarView.getImageList().get(i);
            //设置角标的id和是否拖动
            efImage.setNodeId(id, draggable);
            if (efImage.getBadgeView() == null) {
                QBadgeView badgeView = new QBadgeView(TabBottomActivity.this);
                badgeView.bindTarget(efImage);
                efImage.setNodeId(id, draggable);

                efImage.initBadgeView(badgeView);
            }
            efImage.setBadgeCount(unReadCount);
        }
    }

    //清除角标
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onClearBadgeEvent(ClearBadgeEvent event) {
        BadgeUtil.clearBadge(event.getNodeId());
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        int fromUserId = Integer.parseInt(event.getUserID());
        byte chatType = event.getChatType();
        boolean mustRefresh = event.isRefreshAll();
        Long a1 = System.currentTimeMillis();
        for (int i = 0; i < mainMenuList.size(); i++) {
            StubObject stubObject = mainMenuList.get(i);
            String id = (String) stubObject.getID();
            //配置文件是否该tab的角标可拖动
            boolean draggable = stubObject.getString("badgeDraggable", "false").equals("true");
            List chatIDs = BadgeUtil.badgeMap.get(id);
            if (!mustRefresh) {
                if (!BadgeUtil.isNeedRefreshBadge(chatIDs, fromUserId, chatType)) {
                    continue;
                }
            }
            int unReadCount = BadgeUtil.getCount(id);
            EFImage efImage = tabBarView.getImageList().get(i);
            efImage.setNodeId(id, draggable);
            if (efImage.getBadgeView() == null) {
                QBadgeView badgeView = new QBadgeView(TabBottomActivity.this);
                badgeView.bindTarget(efImage);
                efImage.setNodeId(id, draggable);
                efImage.initBadgeView(badgeView);
            }
            efImage.setBadgeCount(unReadCount);
        }

        int totalUnReadNum = 0;
        for (int i = 0; i < mainMenuList.size(); i++) {
            EFImage efImage = tabBarView.getImageList().get(i);
            int badgeNum = efImage.getBadgeCount();
            totalUnReadNum += badgeNum;
        }
        me.leolin.shortcutbadger.ShortcutBadger.applyCount(getApplicationContext(), totalUnReadNum);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1, sticky = true)
    public void onSolveMessageEvent(SystemInitOverEvent event) {
        BadgeUtil.initBadge();
        initBadge();
        ((BaseApp) getApplicationContext()).setSystemInited(true);

    }

    @Deprecated
    private void updateBadge(int position) {
        String appIdArrayString = EnvironmentVariable.getProperty("Badge" + position, "");
        int unReadCount = 0;
        if (!appIdArrayString.equals("")) {

            String[] appIdArray = appIdArrayString.split(",");
            //过滤空字符串
            for (int j = 0; j < appIdArray.length; j++) {
                String appId = appIdArray[j];
                if (appId.equals("")) {
                    continue;
                }
            }
            for (int j = 0; j < appIdArray.length; j++) {
                String appId = appIdArray[j];
                if (appId.equals("")) {
                    continue;
                }
                int unRead = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(appId), (byte) 0);
                unReadCount += unRead;
            }
        } else {
            unReadCount = 0;
        }
        LinearLayout ll = (LinearLayout) ((LinearLayout) tabBarView.getChildAt(1)).getChildAt(position);
        View v = ll.getChildAt(0);

        BadgeView badgeView = null;
        try {
            badgeView = (BadgeView) tabBarView.findViewWithTag("badge" + position);
        } catch (Exception e) {

        }

        if (badgeView == null) {

            return;
        }
        if (unReadCount > 99) {
            badgeView.setText("99+");
        } else {
            badgeView.setText(unReadCount + "");
        }
        me.leolin.shortcutbadger.ShortcutBadger.applyCount(context, unReadCount);
        badgeView.setBadgeBackgroundColor(getResources().getColor(
                R.color.chat_red));
        if (unReadCount <= 0 && unReadCount != -1) {
            badgeView.setVisibility(View.INVISIBLE);
        } else {
            badgeView.show();
        }
    }

    /**
     * 初始化DrawerLayout
     */
    private void initDrawerLayout() {
        //设置允许打开左边抽屉
        getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
        if (getSupportFragmentManager().findFragmentByTag("tag_LeftDrawerFragment") == null) {//避免出现划出左侧抽屉空白问题//if (savedInstanceState == null) {
            //设置左边抽屉Fragment
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(getDrawerLayoutLeftLayoutResId(), new LeftDrawerFragment(), "tag_LeftDrawerFragment").commit();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //初始化手机的push功能 获取token(反射实现)
        try {

            //清除小米push 角标
            reflectPushManager.method("clearPushNotification");
        } catch (Exception e) {
            LogUtils.e("PushManager初始化失败，可能不支持推送");
        }
        //！！！启动服务(再onResume中启动，防止这种情况：Activity处于前台，service先于Activity被回收掉)
        try {
            startService(new Intent(this, MessageService.class));

            if (!ServiceUtils.isServiceRunning(getApplicationContext(), SystemInfoService.class.getCanonicalName())) {
                String userID = EnvironmentVariable.getUserID();
                if (userID != null && !"".equals(userID)) {
                    startService(new Intent(this, SystemInfoService.class));
                }
            }
            if (!ServiceUtils.isServiceRunning(getApplicationContext(), OSPService.class.getCanonicalName())) {
                startService(new Intent(this, OSPService.class));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //初始化悬浮窗服务
        initFloatWindow(false);
        initDrawerLayout();
        if ("OSPMobileTZu".equals(EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID))) {
            WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            if ("yes".equals(SPUtils.get(this, "isShowDisclaimerDialog", ""))) {
                disclaimerDialog = new DisclaimerDialog(this, R.style.MyDialog);
                disclaimerDialog.show();
                disclaimerDialog.setDisclaimerDialogTitle("糖足App服务协议");
                disclaimerDialog.setCancelable(false);
                disclaimerDialog.setCancelOrAgreeButtonShowOrHide(false);
                disclaimerDialog.setContentContainerHeight((int) (wm.getDefaultDisplay().getHeight() * 0.6));
                disclaimerDialog.setDisclaimerContentText(getResources().getString(R.string.mzsm));
                disclaimerDialog.setCloseButtonShowOrHide(true);
                disclaimerDialog.setLeftButtonText("拒绝");
                disclaimerDialog.setRightButtonText("同意");
//                EnvironmentVariable.setProperty("isShowDisclaimerDialog", "no");
                SPUtils.put(TabBottomActivity.this, "isShowDisclaimerDialog", "false");
            }
        }

    }


    private void initData() {
        mySelf = this;
    }


    @Override
    public void onBackPressed() {
        if (fragmentManager.getBackStackEntryCount() != 0) {
            fragmentManager.popBackStack();
            return;
        }
        if (System.currentTimeMillis() - lastClickBackTime > 3000) {
            ToastUtils.showShort(R.string.mobile_lib_press_back_again_exit);
            lastClickBackTime = System.currentTimeMillis();
        } else {

            moveTaskToBack(false);
        }
    }

    private void initWebview() {
        // TODO Auto-generated method stub
        MyStaticWebView.newInstance(TabBottomActivity.this
                .getApplicationContext());
        //Log.i("TimeCheck","登录初始化webview所用时间————————"+(System.currentTimeMillis() - currentTime));
        MyStaticWebView.getWv().setJsToandroidCallBack(
                new ESPWebView.JsToandroidCallBack() {
                    @Override
                    public void html5initover() {
                    }
                });
        MyStaticWebView.getWv().setEspContext(this);
    }

    /**
     * 初始化UI
     */
    private void initView() {

        //加载配置文件
        if (mainMenuList == null) {
//            mainMenuList = CommonMethodUtil.getTab_Menu_FromXml();
            mainMenuList = getMain_Menu_FromXml();
        }

        makeMainMenu();
    }

    /**
     * 初始化UI
     */
    private void refreshView() {
        //加载配置文件
//        MenuList.clearRegistry();
        Registry.clearRegistry();
        OptionParser.getInstance().release();
//        mainMenuList = CommonMethodUtil.getTab_Menu_FromXml();
        mainMenuList = null;
        initView();
        ////  除消息页和通讯录两页其他的角标
        BadgeUtil.initBadge();
        initBadge();
//        //控制消息页和通讯录两页的角标
//        initBadge2();
        //mainMenuList = getMain_Menu_FromXml();
        //makeMainMenu();

    }

    /**
     * 加载完主菜单之后调用, 生存主菜单布局
     */
    private void makeMainMenu() {
        if (mainMenuList == null) {
            Toast.makeText(AppContext.getInstance(), ResStringUtil.getString(R.string.common_text_http_request_data_fail), Toast.LENGTH_SHORT).show();
            this.finish();
            return;
        }
        cachedFragments = new BaseFragment[mainMenuList.size()];
        loadBottomBar(mainMenuList);
    }

    private void loadBottomBar(List<StubObject> espMenuList) {
        tabBarView = new TabBarNew(this, espMenuList);
        if (tabBarView.getTopOutPosition() != -1) {
            this.changeNavigationHeight();
        }
        mBottomBar = this.getBottomBar();
        mBottomBar.removeAllViews();
        mBottomBar.setVisibility(View.VISIBLE);

        FrameLayout.LayoutParams tabParams = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                SizeUtils.dp2px(50));
        tabParams.gravity = Gravity.BOTTOM;
        mBottomBar.addView(tabBarView, tabParams);
        tabBarView.setOnCurrentTabChangedListener(this);

        //旧方式加载fragment yqs
//        currentTabIndex = DEFAULT_ININT_TAB_INDEX;
//        willHideFragment = willShowFragment;
//        willShowFragment = initAndCacheFragment(currentTabIndex);
//        showFragment(willShowFragment);
//        CheckUpdateHandler.sendEmptyMessage(6);


        //获取应用初始要展示的菜单index
        currentTabIndex = getDefaultDisplayIndex();
        if (getIntent().hasExtra("shareToZone")) {
            tabBarView.setCurrentTab(1);
            currentTabIndex = 1;
        }
        showPageByIndex(currentTabIndex);
    }

    /**
     * 获取应用打开时，默认显示第几个tab页面
     * 目前是从配置文件读取，可以重写这个方法返回相应的index
     *
     * @return
     */
    protected int getDefaultDisplayIndex() {
        int defaultPosition = tabBarView.getDefaultSelectedTab();
        return defaultPosition;
    }

    @Override
    public void onCurrentTabChanged(int index) {
        recordClickMenuNum++;
        //TODO 判断是否是试用版
        boolean isTRY = false;
        if (recordClickMenuNum >= 5 && isTRY) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到构造器
            builder.setTitle("提示"); //设置标题
            builder.setMessage("试用版！请联系管理员。"); //设置内容
            builder.setIcon(R.drawable.wechat_icon_launcher);//设置图标，图片id即可
            builder.setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() { //设置确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss(); //关闭dialog
                    // Toast.makeText(TabBottomActivity.this, "确认" + which, Toast.LENGTH_SHORT).show();
                }
            });
            //参数都设置完成了，创建并显示出来
            builder.create().show();
        }
        showPageByIndex(index);
    }

    private void showPageByIndex(int index) {
        StubObject mainMenuItem = mainMenuList.get(index);
        String isActivity = mainMenuItem.getString("isActivity", "");
        if (isActivity.equals("true")) {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = null;
            try {
                List<StubObject> subMenus = Registry.getRegEntryList((String) mainMenuItem.getID());
                Hashtable menuTable = mainMenuItem.getStubTable();
                StubObject stubObject = subMenus.get(0);
                String AndroidShow = stubObject.getString("AndroidShow", "");
                clazz = loader.loadClass(AndroidShow);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (clazz != null) {
                startActivity(new Intent(this, clazz));
            }
        } else {
            showFragment(index);
        }
    }

    public View getBottomView(int index) {
        View v = ((LinearLayout) tabBarView.getChildAt(1)).getChildAt(index);

        View badge = tabBarView.findViewWithTag("badge" + index);
        if (badge != null) {
            System.out.println(".....判断badage..............." + index);
            ((ViewGroup) badge.getParent()).removeView(badge);
        }
        return v;
    }

    public void showFragment(int index) {
        Log.i("", "test-----====================TabBottomActivity: onCurrentTabChanged:位置：" + index);
        // 缓存并显示fragment
        FragmentTransaction ft = obtainFragmentTransaction(index);
        if (cachedFragments[index] != null) { // 取缓存
            willShowFragment = cachedFragments[index];
        } else {
            willShowFragment = initAndCacheFragment(index);
            ft.add(R.id.mainContent, willShowFragment);
        }
        getCurrentFragment().onPause(); // 暂停当前tab
        if (willShowFragment.isAdded()) {
            willShowFragment.onStart(); // 启动目标tab的onStart()
        } else {
//            ft.add(R.id.mainContent, willShowFragment);
        }
        showTab(ft, index); // 显示目标tab
        // ft.commit();
        //允许状态值丢失，解决一个闪退问题
//        ft.commitAllowingStateLoss();
//        currentIndex = index;


    }

    public Fragment getCurrentFragment() {
        return cachedFragments[currentTabIndex];
    }


    /**
     * 创建并且缓存Fragment
     *
     * @param index
     */
    private BaseFragment initAndCacheFragment(int index) {
        StubObject mainMenuItem = mainMenuList.get(index);
        AbFragmentManager abFragmentManager = new AbFragmentManager(this);
        // 根据viewtype的类型得到
        BaseFragment frag = abFragmentManager.getFragment(mainMenuItem);
        frag.setBadgeType("" + index);
        cachedFragments[index] = frag; // 缓存
        frag.setAlone(false);
        return frag;
    }

    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        return ft;
    }


    /**
     * 切换TAB(先隐藏，后显示)
     *
     * @param
     */
    private void showTab(FragmentTransaction ft, int index) {
//        FragmentTransaction ft = obtainFragmentTransaction(index);
        willShowFragment = cachedFragments[index];
        willHideFragment = cachedFragments[currentTabIndex];
        if (willHideFragment != null && !willShowFragment.equals(willHideFragment)) {
            ft.hide(willHideFragment);
        }

        if (willShowFragment != null) {
            ft.show(willShowFragment);
            // ft.replace(R.id.mainContent, willShowFragment, willShowFragment.getClass().getName());
        }
        ft.commitAllowingStateLoss();
        currentTabIndex = index; // 更新目标tab为当前tab
        tabBarView.setCurrentTabColor(index);
        TabBarNew.mCurrentTabIndex = index;
        mBottomBar.onTabChanged(index);
    }

    /**
     * 显示fragment
     */
//    public void showFragment(final Fragment frag) {
//
//
//        FragmentTransaction tra = fragmentManager.beginTransaction();
//        //tra.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//
//        tra.replace(R.id.mainContent, frag, frag.getClass().getName());
//        tra.commit();
//
//    }
    @Override
    protected void onPause() {
        super.onPause();
    }


    // ----------------提供接口--------------------
    public static TabBottomActivity getInstance() {
        return mySelf;
    }


    public void jumpAndStoreStack(Fragment frag) {
        if (frag == null) {
            return;
        }
        FragmentTransaction trasaction = fragmentManager.beginTransaction();
        trasaction.add(R.id.mainContent, frag, frag.getClass().getName());
        trasaction.addToBackStack(null);
        trasaction.commit();
    }

    public void popBackStack() {
        fragmentManager.popBackStack();
    }

    public TabBarNew getTb() {
        return tabBarView;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        //防止被回收
        super.onSaveInstanceState(outState);
        outState.putSerializable("databack", (Serializable) mainMenuList);
        outState.putInt("index", currentIndex);
//        outState.putSerializable("loginResultRO",loginResultRO);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        System.out.println("currentIndex=====" + currentIndex);
        // System.out.println(mainMenuList.size());
        if (mainMenuList == null) {
            getMain_Menu_FromXml();
        }
    }

    public List<StubObject> getMain_Menu_FromXml() {
//        File file = new File(ResLoadManager.getTabMenuPath() + "/"
//                + "Tab_Menu.xml");
//        MenuParse.getMenu(file);
//            mainMenuList = MenuList.getMenuList(KEY_MENU_ROOT);
        mainMenuList = Registry.getRegEntryList(KEY_MENU_ROOT);
//            defaultMenuList = MenuList.getMenuList("DefaultOpenMenu");
        defaultMenuList = Registry.getRegEntryList("DefaultOpenMenu");

        ResLoadManager.loadMultiLanguageMenu();
        if (mainMenuList == null && defaultMenuList != null) {
            mainMenuList = defaultMenuList;
        }
        MenuGnqxUtil.handleGNQX(mainMenuList);//处理功能权限
        return mainMenuList;
    }

    @Override
    public void refreshNotice() {
        if (willShowFragment instanceof PagerSlidingTabFragment) {
            if (((PagerSlidingTabFragment) willShowFragment).getAdapter().getCurrentFragment() instanceof MainFragment) {
                ((MainFragment) ((PagerSlidingTabFragment) willShowFragment).getAdapter().getCurrentFragment()).refreshGrid();
            }
        }
        if (willShowFragment instanceof PagerSlidingTab2Fragment) {
            if (((PagerSlidingTab2Fragment) willShowFragment).getAdapter().getCurrentFragment() instanceof MainFragment) {
                ((MainFragment) ((PagerSlidingTab2Fragment) willShowFragment).getAdapter().getCurrentFragment()).refreshGrid();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        Log.i("", "-------onActivityResult:" + TAG);
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (onTabBottomActivityResultListener != null) {
                onTabBottomActivityResultListener.onTabBottomActivityResult(requestCode, resultCode, data);
            }
        } else if (resultCode == FloatWindowService.REQUEST_CODE_PERMISSON_OVERLAY) {
            //请求弹框权限
            initFloatWindow(true);
        }
    }

    private void initFloatWindow(boolean isOnactivityresult) {
        if (FloatWindowService.checkOverLayPermission(this, isOnactivityresult)) {
            FloatWindowService.startFloatService(this);
        }
    }

    public interface TabBottomActivityResultListener {
        void onTabBottomActivityResult(int requestCode, int resultCode, Intent data);
    }


    public void setOnTabBottomActivityResultListener(
            TabBottomActivityResultListener onTabBottomActivityResultListener) {
        this.onTabBottomActivityResultListener = onTabBottomActivityResultListener;
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.w("--", TAG + "-----onStop--");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //TODO

        EventBus.getDefault().unregister(this);

//        fixbug 梅俊
        if ("OSPMobileTZu".equals(EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID))) {
            EnvironmentVariable.setProperty("isShowDisclaimerDialog", "yes");
            disclaimerDialog.unRegisterOnDisclaimerDialogLisener();
        }
        mySelf = null;
    }


    Handler CheckUpdateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    initView();
                    break;
                case 1:
                    //   refreshView();
                    break;
                case 6://登陆后显示设定的tab页
                    int defaultPosition = tabBarView.getDefaultSelectedTab();
                    if (defaultPosition != 0) {
                        showPageByIndex(defaultPosition);
                        //showFragment(defaultPosition);
                        tabBarView.setCurrentTabColor(defaultPosition);
                        tabBarView.mCurrentTabIndex = defaultPosition;
                    }

                    break;
            }

            super.handleMessage(msg);
        }
    };

    private void stopAllService() {
        //TODO 停掉MessageService
        this.stopService(new Intent(this, OSPService.class));
        this.stopService(new Intent(this, WatchService.class));
        this.stopService(new Intent(this, MessageService.class));
        this.stopService(new Intent(this, SystemInfoService.class));
        this.stopService(new Intent(this, DownLoadService.class));
    }

    //处理通过消息发送的app以及资源文件更新事件 yqs
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowDataEvent(UpdateResEvent event) {
        if ("appupdate".equals(event.getType())) {
            String version = event.getVersion();
            String updateNote = event.getUpdateNote();
            String url = event.getUrl();
            Log.i(TAG, "收到app更新的消息");
            if (apkUpdateManager.checkIsNeedToDown(version)) {//如果版本不一致
                boolean isForceUpdateApk = apkUpdateManager.checkIsNeedForceDown(version);//是否需要强制升级
                apkUpdateManager.downAPK(TabBottomActivity.this, null, updateNote, url, apkUpdateManager, isForceUpdateApk, CheckUpdateHandler);
            }

        } else if ("appresupdate".equals(event.getType())) {
            String version = event.getVersion();
            String updateNote = event.getUpdateNote();
            Log.i(TAG, "收到app资源更新的消息");
            final RESUpdateManager resUpdateManager = new RESUpdateManager();
            if (resUpdateManager.checkIsNeedToDown(version)) {//如果版本不一致
                apkUpdateManager.downAPPRes(TabBottomActivity.this, updateNote, resUpdateManager, null, CheckUpdateHandler);
            }
        }
    }

    //刷新view
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshViewEvent(RefreshViewEvent event) {
        if (event.getRefreshViewID() == RefreshViewEvent.VIEW_TABOTTOMACTIVITY) {
            // 皮肤存在，加载新皮肤
            File file = new File(SKIN_DIR, "mobile.skin");
            if (file != null && file.exists()) {
                SkinCompatManager.getInstance().loadSkin("mobile.skin", null, CustomSDCardLoader.SKIN_LOADER_STRATEGY_SDCARD);
            }
            //刷新界面
            refreshView();
        }
    }
}
